//
//  WJController+extension.swift
//  WJWEIBO
//
//  Created by 文杰 许                       on 2018/6/25.
//  Copyright © 2018年 文杰 许                      . All rights reserved.
//

import UIKit

extension UIViewController
{
    /// 获取当前控制器
    class func currentViewController() -> UIViewController
    {
        let vc = UIApplication.shared.keyWindow?.rootViewController
        return UIViewController.findBestViewController(vc: vc!)
    }
    private class func findBestViewController(vc : UIViewController) -> UIViewController
    {
        
        if vc.presentedViewController != nil
        {
            return UIViewController.findBestViewController(vc: vc.presentedViewController!)
        }
        else if vc.isKind(of:UISplitViewController.self)
        {
            let svc = vc as! UISplitViewController
            if svc.viewControllers.count > 0
            {
                return UIViewController.findBestViewController(vc: svc.viewControllers.last!)
            }
            else
            {
                return vc
            }
        }
        else if vc.isKind(of: UINavigationController.self)
        {
            let nvc = vc as! UINavigationController
            if nvc.viewControllers.count > 0
            {
                return UIViewController.findBestViewController(vc: nvc.topViewController!)
            }
            else
            {
                return vc
            }
        }
        else if vc.isKind(of: UITabBarController.self)
        {
            let tvc = vc as! UITabBarController
            if (tvc.viewControllers?.count)! > 0
            {
                return UIViewController.findBestViewController(vc: tvc.selectedViewController!)
            }
            else
            {
                return vc
            }
        }
        else
        {
            return vc
        }
    }
}
